import axios from "axios";
import { MessageBox, Message } from "element-ui";
import qs from "qs";

const service = axios.create({
  withCredentials: false, // send cookies when cross-domain requests
  crossDomain: true,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  },
  timeout: 6000 // request timeout    请求超时时间
});

service.defaults.retry = 3;
service.defaults.retryDelay = 2000;

service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    // console.log(error) // for debug
    return Promise.reject(error);
  }
);
service.interceptors.response.use(
  response => {
    const res = response.data;
    // console.log(res)
    if (res.code !== 0) {
      if (res.code === 2) {
        MessageBox.confirm(res.message, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error"
        })
          .then(() => {
            localStorage.removeItem("userInfo");
            this.$router.replace({ path: "/login" });
          })
          .catch(() => {});
      } else {
        MessageBox.confirm(res.message, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error"
        })
          .then(() => {})
          .catch(() => {});
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error);
  }
);

// 返回错误时拦截，并尝试重试
service.interceptors.response.use(undefined, function axiosRetryInterceptor(
  err
) {
  var config = err.config;
  // If config does not exist or the retry option is not set, reject
  if (!config || !config.retry) return Promise.reject(err);

  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0;

  // Check if we've maxed out the total number of retries
  if (config.__retryCount >= config.retry) {
    // Reject with the error
    Message({
      message: err.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(err);
  }

  // Increase the retry count
  config.__retryCount += 1;

  // Create new promise to handle exponential backoff
  var backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, config.retryDelay || 1);
  });
  config.data = qs.parse(config.data);
  // Return the promise in which recalls axios to retry the request
  return backoff.then(function() {
    return service(config);
  });
});

export default service;
